package com.wgh.product.controller;

import com.wgh.common.vo.Result;
import com.wgh.common.vo.PageResult;
import com.wgh.product.dto.ProductReviewDTO;
import com.wgh.product.entity.shop.ProductReview;
import com.wgh.product.service.ProductReviewService;
import com.wgh.product.converter.ProductReviewConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品评价控制器
 * 提供商品评价相关的RESTful API
 */
@RestController
@RequestMapping("/api/product-review")
public class ProductReviewController {

    @Autowired
    private ProductReviewService productReviewService;

    @Autowired
    private ProductReviewConverter productReviewConverter;

    /**
     * 分页查询商品评价
     */
    @GetMapping("/page")
    public Result<PageResult<ProductReviewDTO>> getReviewPage(
            @RequestParam(required = false) Map<String, Object> params,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            if (params == null) {
                params = new HashMap<>();
            }
            PageResult<ProductReview> pageResult = productReviewService.getReviewPage(params, pageNum, pageSize);
            PageResult<ProductReviewDTO> dtoPageResult = new PageResult<>();
            dtoPageResult.setTotal(pageResult.getTotal());
            dtoPageResult.setList(productReviewConverter.toDTOList(pageResult.getList()));
            return Result.success(dtoPageResult);
        } catch (Exception e) {
            return Result.error("获取商品评价列表失败：" + e.getMessage());
        }
    }

    /**
     * 根据商品ID查询评价列表
     */
    @GetMapping("/product/{productId}")
    public Result<PageResult<ProductReviewDTO>> getReviewsByProductId(
            @PathVariable Long productId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            PageResult<ProductReview> pageResult = productReviewService.getReviewsByProductId(productId, pageNum, pageSize);
            PageResult<ProductReviewDTO> dtoPageResult = new PageResult<>();
            dtoPageResult.setTotal(pageResult.getTotal());
            dtoPageResult.setList(productReviewConverter.toDTOList(pageResult.getList()));
            return Result.success(dtoPageResult);
        } catch (Exception e) {
            return Result.error("获取商品评价列表失败：" + e.getMessage());
        }
    }

    /**
     * 根据用户ID查询评价列表
     */
    @GetMapping("/user/{userId}")
    public Result<PageResult<ProductReviewDTO>> getReviewsByUserId(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            PageResult<ProductReview> pageResult = productReviewService.getReviewsByUserId(userId, pageNum, pageSize);
            PageResult<ProductReviewDTO> dtoPageResult = new PageResult<>();
            dtoPageResult.setTotal(pageResult.getTotal());
            dtoPageResult.setList(productReviewConverter.toDTOList(pageResult.getList()));
            return Result.success(dtoPageResult);
        } catch (Exception e) {
            return Result.error("获取用户评价列表失败：" + e.getMessage());
        }
    }

    /**
     * 根据评价ID获取评价详情
     */
    @GetMapping("/{id}")
    public Result<ProductReviewDTO> getReviewDetail(@PathVariable Long id) {
        try {
            ProductReview productReview = productReviewService.getReviewDetail(id);
            if (productReview == null) {
                return Result.success(null);
            }
            return Result.success(productReviewConverter.toDTO(productReview));
        } catch (Exception e) {
            return Result.error("获取评价详情失败：" + e.getMessage());
        }
    }

    /**
     * 新增商品评价
     */
    @PostMapping
    public Result<Boolean> addReview(@RequestBody ProductReviewDTO productReviewDTO) {
        try {
            ProductReview productReview = productReviewConverter.toEntity(productReviewDTO);
            boolean result = productReviewService.addReview(productReview);
            return result ? Result.success(true) : Result.error("新增评价失败");
        } catch (Exception e) {
            return Result.error("新增评价失败：" + e.getMessage());
        }
    }

    /**
     * 更新评价状态
     */
    @PutMapping("/{id}/status")
    public Result<Boolean> updateReviewStatus(@PathVariable Long id, @RequestParam Integer status) {
        try {
            boolean result = productReviewService.updateReviewStatus(id, status);
            return result ? Result.success(true) : Result.error("更新评价状态失败");
        } catch (Exception e) {
            return Result.error("更新评价状态失败：" + e.getMessage());
        }
    }

    /**
     * 批量更新评价状态
     */
    @PutMapping("/status/batch")
    public Result<Boolean> batchUpdateReviewStatus(@RequestParam List<Long> ids, @RequestParam Integer status) {
        try {
            boolean result = productReviewService.batchUpdateReviewStatus(ids, status);
            return result ? Result.success(true) : Result.error("批量更新评价状态失败");
        } catch (Exception e) {
            return Result.error("批量更新评价状态失败：" + e.getMessage());
        }
    }

    /**
     * 回复评价
     */
    @PutMapping("/{id}/reply")
    public Result<Boolean> replyReview(@PathVariable Long id, @RequestParam String replyContent) {
        try {
            boolean result = productReviewService.replyReview(id, replyContent);
            return result ? Result.success(true) : Result.error("回复评价失败");
        } catch (Exception e) {
            return Result.error("回复评价失败：" + e.getMessage());
        }
    }

    /**
     * 根据商品ID统计评价信息
     */
    @GetMapping("/statistics/product/{productId}")
    public Result<Map<String, Object>> getReviewStatisticsByProductId(@PathVariable Long productId) {
        try {
            Map<String, Object> statistics = productReviewService.getReviewStatisticsByProductId(productId);
            return Result.success(statistics);
        } catch (Exception e) {
            return Result.error("获取评价统计信息失败：" + e.getMessage());
        }
    }

    /**
     * 获取有图评价列表
     */
    @GetMapping("/image/product/{productId}")
    public Result<PageResult<ProductReviewDTO>> getImageReviewsByProductId(
            @PathVariable Long productId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            PageResult<ProductReview> pageResult = productReviewService.getImageReviewsByProductId(productId, pageNum, pageSize);
            PageResult<ProductReviewDTO> dtoPageResult = new PageResult<>();
            dtoPageResult.setTotal(pageResult.getTotal());
            dtoPageResult.setList(productReviewConverter.toDTOList(pageResult.getList()));
            return Result.success(dtoPageResult);
        } catch (Exception e) {
            return Result.error("获取有图评价列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取商品的平均评分
     */
    @GetMapping("/average-score/product/{productId}")
    public Result<Double> getAverageScoreByProductId(@PathVariable Long productId) {
        try {
            Double averageScore = productReviewService.getAverageScoreByProductId(productId);
            return Result.success(averageScore);
        } catch (Exception e) {
            return Result.error("获取平均评分失败：" + e.getMessage());
        }
    }

    /**
     * 批量查询评价
     */
    @GetMapping("/batch")
    public Result<List<ProductReviewDTO>> getReviewsByIds(@RequestParam List<Long> ids) {
        try {
            List<ProductReview> productReviews = productReviewService.listByIds(ids);
            return Result.success(productReviewConverter.toDTOList(productReviews));
        } catch (Exception e) {
            return Result.error("批量查询评价失败：" + e.getMessage());
        }
    }
}